package com.itxh.factory;

import com.itxh.model.BeanDefinition;
import com.itxh.registry.SingletonBeanRegistry;

public abstract class AbstractBeanFactory extends SingletonBeanRegistry implements BeanFactory{

//    // 用来存储bean的对象
//    private Map<String,Object> singletonObjects = new HashMap<>();

    @Override
    public Object getBean(String name) {
        try {

//            Object bean = singletonObjects.get(name);
            Object bean = getSingleton(name);
            if (bean != null) {
                return bean;
            }
            BeanDefinition bd = getBeanDefinition(name);
            if (bd == null) {
                return null;
            }
            String scope = bd.getScope();
            if ("singleton".equals(scope)){
                bean = doCreateBean(bd);
                addSingleton(name,bean);
//                singletonObjects.put(name,bean);
            }else if ("prototype".equals(scope)){
                bean = doCreateBean(bd);
            }

            return bean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected abstract BeanDefinition getBeanDefinition(String name);

    protected abstract Object doCreateBean(BeanDefinition bd) throws Exception;
}
